// pages/seach/seach.js
//index.js
//获取应用实例
const app = getApp()
var isChoiceness = true;
var page = 1;
Page({
  data: {
    seachkey: '',
    categoryId: '',
    winWidth: 0,
    winHeight: 0,
    clipboard: '',
    cbitem: [],
    cbsw: false,
    isFind: false,
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    // tab切换  
    currentTab: 0,
    items: [],
    todayitems: [],
    skitems: [],
    hotitems: [],
    sptodayitems: [],
    favimg: {
      imgUrl: 'https://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/ico5.png',
      curUrl: 'https://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/ico5hover.png',
    },
    sessionId: app.globalData.sessionId,
    searchKeyword: '',  //需要搜索的字符  
    searchSongList: [], //放置返回数据的数组  
    isFromSearch: true,   // 用于判断searchSongList数组是不是空数组，默认true，空的数组  
    searchPageNum: 1,   // 设置加载的第几次，默认是第一次  
    todayPageNum: 1,
    skPageNum: 1,
    callbackcount: 15,      //返回数据的个数  
    searchLoading: true, //"上拉加载"的变量，默认false，隐藏  
    toadysearchLoading: true,
    sksearchLoading: true,
    searchLoadingComplete: false,  //“没有数据”的变量，默认false，隐藏
    isIphoneX: false,
    onlyWx: false,
    statusBarHeight: app.globalData.statusBarHeight,
    detailedtc: false,
    sharetc: false,
    sharepic: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc2.png',
    sharenpic: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc6.png',
    shareData: [],
    news: app.globalData.newnotice,
    oldsharetc: false,
    oldsharepic: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc3.png',
    sharesucctc: false,
    sharesucc: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharesuccess.png',
    sharesuccData: [],
    socketMessage: [],
    formId: '',
    socketMessagesw: false,
    sharepictc: false,
    shareimg: '',
    loading: true,
    sharentc: false,
    itemIsShow: false
  },
  onShareAppMessage: function (res) {
    var path = '/pages/index/index?userId=' + app.globalData.userId
    var imageUrl = 'https://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharepic.jpg'
    app.globalData.newnotice = true
    this.setData({
      news: app.globalData.newnotice
    });
    var title = '京多多'
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
      var str = res.target.dataset.share.title
      path = path + '?sku=' + res.target.dataset.share.skuId
      title = str.slice(0, 14) + '...'
      imageUrl = res.target.dataset.share.image
      this.setData({
        oldsharetc: false
      })
      this.postformid(res.target.dataset.share.skuId)
    }
    return {
      title: title,
      path: path,
      imageUrl: imageUrl
    }
  },
  onLoad: function () {
    var that = this;
    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    let isIphoneX = app.globalData.isIphoneX;
    this.setData({
      isIphoneX: isIphoneX
    })
    this.setData({
      seachkey: '女',
      categoryId: app.globalData.seachid
    });
    console.log(this.data.seachkey, this.data.categoryId)
    this.getitemdata(this.data.seachkey, this.data.categoryId)
  },
  onShow: function () {
    var that = this;
    wx.getClipboardData({
      success: function (res) {
        console.log('res.data:' + res.data)
        console.log('that.data.clipboard:' + that.data.clipboard)
        var str = res.data;
        var urlold = res.data.split("?")[0]
        var urlnew = that.data.clipboard.split("?")[0]
        if (str.indexOf("jd.com") != -1) {
          if (urlold !== urlnew) {
            that.setData({
              clipboard: res.data
            });
            that.getclipboarddata(res.data)
          }
        } else if (str.match(".*[0-9]{6,18}.*")) {
          if (res.data !== that.data.clipboard) {
            that.setData({
              clipboard: res.data
            });
            that.getclipboarddata(res.data)
          }
        }

      }
    })
  },
  postformid(skuId) {
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId,
        skuId: skuId,
        formId: that.data.formId
      },
      url: app.globalData.url + "/app/v2/goods/getShareLink",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  closesptc() {
    this.setData({
      sharepictc: false,
      shareimg: ''
    });
  },
  saveimg() {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareimg,
      success(res) {
        wx.hideToast()
        app.globalData.newnotice = true
        that.setData({
          news: app.globalData.newnotice
        });
        console.log(that.data.news)
        wx.showModal({
          title: '提示',
          content: '分享图已经存到您的相册',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.setData({
                sharepictc: false,
                shareimg: ''
              });
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  },
  buybtn(e) {
    console.log(e)
    app.globalData.item = e.currentTarget.dataset.item
    console.log(app.globalData.item)

    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        formid: e.detail.formId,
        sessionId: app.globalData.sessionId
      },
      url: app.globalData.url + "/wxa/user/uploadFormid",
      async: true,
      timeout: 10000,
      success: function (data) {
        if (e.currentTarget.dataset.item.is99) {
          wx.navigateTo({
            url: '/pages/activeitemdetail/activeitemdetail'
          })
        } else {
          wx.navigateTo({
            url: '/pages/itemdetail/itemdetail'
          })
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  getclipboarddata(content) {
    wx.showLoading({
      title: '加载中',
    })
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        content: content
      },
      url: app.globalData.url + "/app/v2/goods/clipboardSpirit",
      async: true,
      timeout: 10000,
      success: function (data) {
        wx.hideLoading()
        console.log(data)
        if (data.data.code == 0) {
          if (data.data.data.isFind) {
            that.setData({
              cbitem: data.data.data,
              cbsw: true,
              isFind: true
            });
          } else {
            that.setData({
              cbitem: data.data.data,
              cbsw: true,
              isFind: false
            });
          }
          console.log(that.data.cbitem)
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  close() {
    this.setData({
      cbsw: false
    });
  },
  closetc() {
    this.setData({
      firstuser: false
    });
  },
  closedtc() {
    this.setData({
      detailedtc: false
    });
  },
  activelink() {
    this.setData({
      firstuser: false,
      currentTab: 2,
      sharesucctc: false
    })
  },
  tiptc() {
    this.setData({
      detailedtc: true
    })
  },
  getitemdata(key, categoryId) {
    var that = this
    isChoiceness = true
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        pageNo: that.data.searchPageNum,
        keyword: that.data.seachkey,
        categoryId: categoryId,
        onlyWx: that.data.onlyWx
      },
      url: app.globalData.url + "/app/v2/goods/list",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        that.setData({
          items: data.data.data,
          loading: false,
          itemIsShow: true
        });
        console.log(that.data.items)
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  favitem(e) {
    var that = this
    console.log(e)
    var edata = e.currentTarget.dataset;
    var i = edata.index
    console.log(edata)
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: { skuId: edata.skuid, sessionId: app.globalData.sessionId },
      url: app.globalData.url + "/app/user/collect",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        var array = that.data.items;
        if (edata.iscollect) {
          wx.showToast({
            title: '取消收藏',
            icon: "success"
          })
          var currId = edata.skuid;
          array[i].isCollect = false;
          array[i].collectTotal = array[i].collectTotal - 1;
          that.setData({
            items: array
          });
          return false
        } else {
          wx.showToast({
            title: '收藏成功',
            icon: "success"
          })
          var currId = edata.skuid;
          array[i].isCollect = true;
          array[i].collectTotal = array[i].collectTotal + 1;
          that.setData({
            items: array
          });
          return false
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  itemlink(e) {
    console.log(e)
    var edata = e.currentTarget.dataset
    var that = this
    var content = '<a href="http://www.qq.com" data-miniprogram-appid="appid" data-miniprogram-path="pages/index/index">点击跳小程序</a>'
    var openId = app.globalData.openId
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        skuId: edata.skuid,
        couponId: edata.couponid,
        sessionId: app.globalData.sessionId

      },
      url: app.globalData.url + "/app/goods/wxaSendCoupon",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        wx.request({
          method: "POST",
          header: { "content-type": "application/x-www-form-urlencoded" },
          data: {
            touser: openId,
            msgtype: "text",
            text:
            {
              content: content
            }
          },
          url: 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' + access_token,
          async: true,
          timeout: 10000,
          success: function (res) {
            console.log(res);
          },
          error: function (err) {
            console.log(err);
          }
        });
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  shareSubmit(e) {
    console.log(e)
    if (e.currentTarget.dataset.item.is99) {
      this.setData({
        sharetc: true,
        shareData: e.currentTarget.dataset.item,
        formId: e.detail.formId
      });
    } else {
      this.setData({
        sharentc: true,
        shareData: e.currentTarget.dataset.item,
        formId: e.detail.formId
      });
    }
    console.log(this.data.shareData)
  },

  closestc() {
    this.setData({
      sharetc: false,
      shareData: []
    });
  },
  closesutc() {
    this.setData({
      sharesucctc: false,
      shareData: []
    });
  },
  shareweixinquan(e) {
    var that = this
    var edata = e.currentTarget.dataset.item
    this.postformid(e.currentTarget.dataset.item.skuId)
    wx.showToast({
      title: '生成中...',
      icon: 'loading',
      duration: 2000
    });
    console.log(e)
    var imgbgsrc
    if (edata.is99) {
      imgbgsrc = '/img/picbg3.jpg'
    } else {
      imgbgsrc = '/img/picbg.jpg'
    }
    console.log(imgbgsrc)
    function sharepic(data, link) {
      console.log(data)
      if (data.data.code == 0) {
        var str = edata.title;
        str = str.slice(0, 30)
        var str1 = str.slice(0, 16)
        var str2 = str.slice(17, 30) + '...'
        var format = function (value) {
          var html, _val;
          value = Number(value).toFixed(2);
          if (value == 0) {
            value = 0;
            return html = "<text>0</text>";
          } else {
            value = Number(value).toFixed(2);
          }
          _val = value.split('.');
          return html = _val[0] + '.' + _val[1];
        }
        var price1 = format(edata.price)
        if (edata.coupons) {
          var price2 = format(edata.price - edata.coupons[0].discount)
          var reduce = '券后立省' + edata.coupons[0].discount + '元'
        } else {
          var price2 = format(edata.price)
          var reduce = '券后立省' + 0 + '元'
        }
        wx.getImageInfo({
          src: edata.image,
          success: function (res) {
            console.log(res)
            const sharepic = wx.createCanvasContext('myCanvas')
            var itemimg = res.path
            wx.getImageInfo({
              src: link,
              success: function (res) {
                console.log(res)
                var dcode = res.path
                sharepic.drawImage(imgbgsrc, 0, 0, 1080, 1920)
                sharepic.setFontSize(46)
                sharepic.setTextAlign('center')
                sharepic.setFillStyle('#404142')
                sharepic.fillText(str1, 540, 1013)
                sharepic.fillText(str2, 540, 1083)
                if (edata.tags.length > 0) {
                  sharepic.rect(462, 1137, 164, 54)
                  sharepic.setFillStyle('#ff4564')
                  sharepic.fill()
                  sharepic.setFontSize(35)
                  sharepic.setTextAlign('center')
                  sharepic.setFillStyle('white')
                  sharepic.fillText(edata.tags, 544, 1178)
                }
                sharepic.setFontSize(60)
                sharepic.setTextAlign('center')
                sharepic.setFillStyle('#aaabad')
                sharepic.fillText(price1, 335, 1376)
                sharepic.setFillStyle('#ff4564')
                sharepic.fillText(price2, 750, 1376)
                sharepic.setFontSize(46)
                sharepic.fillText(reduce, 540, 1486)
                sharepic.drawImage(itemimg, 297, 454, 486, 486)
                if (edata.is99) {
                  sharepic.drawImage('/img/freeico.png', 760, 422, 243, 221)
                }
                sharepic.drawImage(dcode, 808, 1646, 236, 236)
                setTimeout(function () {
                  sharepic.draw()
                }, 100)
                setTimeout(function () {
                  wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: 1080,
                    height: 1920,
                    destWidth: 1080,
                    destHeight: 1920,
                    canvasId: 'myCanvas',
                    success: function (res) {
                      console.log(res.tempFilePath)
                      // wx.previewImage({
                      //   current: res.tempFilePath,
                      //   urls: [res.tempFilePath]
                      // })
                      that.setData({
                        sharepictc: true,
                        shareimg: res.tempFilePath,
                        sharetc: false,
                        sharentc: false
                      });
                      console.log('sharetc' + that.data.sharetc)
                    }
                  })
                }, 1000)
              }
            })
          }
        })
      } else {
        wx.redirectTo({
          url: '/pages/index/index'
        })
      }
    }
    var scene = '?userid=' + getApp().globalData.userId + '&skuid=' + e.currentTarget.dataset.item.skuId
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        scene: scene,
        page: 'pages/index/index',
        sessionId: app.globalData.sessionId,
        width: '236',
        auto_color: 'false',
        line_color: '{"r":"0","g":"0","b":"0"}',
        is_hyaline: 'false'
      },
      url: app.globalData.url + "/wxa/qrcode/getUnlimitQrcode",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data.data.qrcodeLink)
        sharepic(data, data.data.qrcodeLink)
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })

  },
  fetchSearchList: function () {
    var that = this;
    var searchPageNum = that.data.searchPageNum,//把第几次加载次数作为参数  
      callbackcount = that.data.callbackcount; //返回数据的个数
    isChoiceness = true
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        pageNo: that.data.searchPageNum,
        keyword: that.data.seachkey,
        categoryId: that.data.categoryId,
        onlyWx: that.data.onlyWx
      },
      url: app.globalData.url + "/app/v2/goods/list",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        console.log(that.data.searchPageNum)
        var num = 10 * (that.data.searchPageNum - 1)
        if (data.data.total > num) {
          var items = that.data.items.concat(data.data.data)
          console.log(items)
          that.setData({
            items: items, //获取数据数组  
            searchLoading: true,   //把"上拉加载"的变量设为false，显示
            loading: false
          });
          console.log(that.data.items)
        } else {
          that.setData({
            searchLoading: false,  //把"上拉加载"的变量设为false，隐藏
            loading: false
          });
          wx.showToast({
            title: '没有更多商品了',
            icon: 'none',
            duration: 2000
          });
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  searchScrollLower: function (e) {
    console.log(e)
    var that = this;
    that.setData({
      loading: true
    });
    if (that.data.searchLoading && !that.data.searchLoadingComplete) {
      that.setData({
        searchPageNum: that.data.searchPageNum + 1,
        todayPageNum: that.data.todayPageNum + 1,
        skPageNum: that.data.skPageNum + 1,
        isFromSearch: false  //触发到上拉事件，把isFromSearch设为为false  
      });
      that.fetchSearchList();
    } else {
      console.log(that.data.searchLoading, that.data.searchLoadingComplete)
      that.setData({
        loading: false
      });
    }
  },
  onPullDownRefresh: function () {
    var that = this;
    console.log("下拉刷新....")
    that.setData({
      searchPageNum: 1,
      todayPageNum: 1,
      skPageNum: 1,
      isFromSearch: true
    });
    that.onLoad()
    wx.stopPullDownRefresh()
  },
  imglink: function (link) {
    wx.redirectTo({
      url: link
    })
  },
  closentc() {
    this.setData({
      sharentc: false,
      shareData: []
    });
  },
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    var keywordcooke = app.globalData.seachrecord,
      keyword = e.detail.value,
      repeat = false;
    console.log('keywordcooke' + keywordcooke)
    for (var i = 0; i < keywordcooke.length; i++) {
      console.log(keywordcooke[i])
      if (keywordcooke[i] == keyword) {
        keywordcooke.splice(i, 1);
        keywordcooke.unshift(keyword)
        repeat = true;
        break;
      }
    }
    if (!repeat) {
      keywordcooke.unshift(keyword)
    }
    console.log('keywordcooke' + keywordcooke)
    wx.setStorage({
      key: "key",
      data: keywordcooke
    })
    app.globalData.seachkey = e.detail.value
    app.globalData.seachid = ''
    console.log(app.globalData.seachkey)
    wx.redirectTo({
      url: '/pages/seachlist/seachlist'
    })
  },
  forminput: function (e) {
    console.log(e)
    this.setData({
      seachkey: e.detail.value,
    });
  },
  back: function () {
    this.setData({
      seachkey: '',
      categoryId: '',
    });
    app.globalData.seachkey = ''
    app.globalData.seachid = ''
    wx.navigateBack()
  },
  cancel: function () {
    wx.redirectTo({
      url: '/pages/itemlist/itemlist'
    })
  },
  reset: function () {
    this.setData({
      seachkey: '',
    });
  }
})






